import fitz
import os
import time
import pdfplumber
import shutil
import zipfile
import os
import datetime
from PIL import Image
from apps.translate.config import pdftojpg_base_path
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.utils import toMd5,saveFile
from django.http import FileResponse
from django.utils.encoding import escape_uri_path
from django.core.signals import request_finished
from apps.translate.signal import deleteSrcData

class PdfToJpgAPIView(APIView):
    def post(self, request):
        data = saveFile(self, request, savepath=pdftojpg_base_path)
        try:
            for i in data:
                # 将pdf一张张切割成jpg
                timestamp = time.time()
                full_path = pdftojpg_base_path+"%s.%s" %(i,'pdf')            # 拼接，得到PDF文件的绝对路径
                doc=fitz.open(full_path)
                pdf = pdfplumber.open(full_path) # 打开一个PDF文件，doc为Document类型，是一个包含每一页PDF文件的列表
                rotate = int(0)  # 设置图片的旋转角度，如果图片方向不对的话改这个
                zoom_x = 1.0  # 设置图片相对于PDF文件在X轴上的缩放比例
                zoom_y = 2.0  # 设置图片相对于PDF文件在Y轴上的缩放比例
                # trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)	#旋转图片，如果图片方向不对的话改前面rotate的旋转角度
                if len(pdf.pages)> 1:  # 获取PDF的页数,如果是多页
                    for pg in range(len(pdf.pages)):
                        page = doc[pg]  # 获得第pg页
                        pm = page.get_pixmap(alpha=False)  # 将其转化为光栅文件（位数）
                        new_full_name = i.split(".")[0]  # 保证输出的文件名不变
                        if not os.path.exists(pdftojpg_base_path+'%s' % new_full_name):
                            os.mkdir(pdftojpg_base_path+'%s' % new_full_name)
                        pm.save(pdftojpg_base_path+"%s/%s-%s.jpg" % (new_full_name, new_full_name, pg))  # 将其输入为相应的图片格式，可以为位图，也可以为矢量图
                        # 我本来想输出为jpg文件，但是在网页中都是png格式（即调用writePNG），再转换成别的图像文件前，最好查一下是否支持
                else:
                    page = doc[0]
                    pm = page.get_pixmap(alpha=False)
                    new_full_name = full_path.split(".")[0]
                    pm.writeImage(pdftojpg_base_path+"%s.jpg" % new_full_name)
        except Exception as e:
            return Response({'code': 4000, 'msg': '转换失败'})   
        return Response({'code': 2000, 'msg': '转换完成', 'data': data})

class GetPdfToJpgAPIView(APIView):
    def post(self, request):
        # 移动转行后的文件夹,如果是多个文件，则返回zip，一个的话直接返回xx.pdf
        if len(request.data)>1:
            secret_dir = toMd5(str(time.time()))
            path = pdftojpg_base_path+"%s"%secret_dir
            os.makedirs(path)
            try:
                for i in request.data:
                     shutil.move(pdftojpg_base_path+str(i)+'/', path)
                file_news = secret_dir +'.zip'
                z = zipfile.ZipFile(pdftojpg_base_path+file_news, 'w', zipfile.ZIP_DEFLATED)
                for dirpath, dirnames, filenames in os.walk(path):
                    fpath = dirpath.replace(path,'') #这一句很重要，不replace的话，就从根目录开始复制
                    fpath = fpath and fpath + os.sep or ''#这句话理解我也点郁闷，实现当前文件夹以及包含的所有文件的压缩
                    for filename in filenames:
                        z.write(os.path.join(dirpath, filename),fpath+filename)
                z.close()
                # shutil.move(secret_dir+'.zip', path)
                response = FileResponse(open(pdftojpg_base_path+file_news, 'rb'))         
                response['Content-Type'] = "application/zip"       
                response['Content-Disposition'] = "attachment;filename*={}".format(escape_uri_path(file_news))
                request_finished.send(sender='pdftojpgs',md5Items=[secret_dir,request.data])   
                return response
            except Exception as e:
                return Response({'code': 4001, 'msg': e.args})
        else:
            file_new = request.data[0]
            out_name = file_new +'.zip'
            file_news = pdftojpg_base_path+file_new +'.zip'
            z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
            for dirpath, dirnames, filenames in os.walk(pdftojpg_base_path+'%s'%file_new):
                fpath = dirpath.replace(pdftojpg_base_path,'') #这一句很重要，不replace的话，就从根目录开始复制
                fpath = fpath and fpath + os.sep or ''#这句话理解我也点郁闷，实现当前文件夹以及包含的所有文件的压缩
                for filename in filenames:
                    z.write(os.path.join(dirpath, filename),file_new + filename)
            z.close()
            response = FileResponse(open(file_news, "rb"))
            response["Content-Type"] = "application/zip"
            response["Content-Disposition"] = "attachment; filename*={}".format(escape_uri_path(out_name))
            request_finished.send(sender='pdftojpg',md5Items=[file_new])   
            return response